#include<stdio.h>
#include<pthread.h>

int ticket=100;
void* Thread_can(void* arg)
{
  pthread_mutex_t *mutex=(pthread_mutex_t*)arg;  //定义互斥锁
  while(1){
    pthread_mutex_lock(mutex);  //加锁
    usleep(10);

    if(ticket>0){
      //进行抢票
      printf("%p 抢到了 %d 号票！\n",pthread_self(),ticket);
      ticket--;
      pthread_mutex_unlock(mutex);  //抢票之后解锁
    }
    else{
      printf("票没有了！\n");
      pthread_mutex_unlock(mutex);  //解锁
      pthread_exit(NULL);   //退出线程
    }
  }
  usleep(1);
  return NULL;
}

int main()
{
  pthread_t tid[4];
  const char*arg="nihaoa";
  int ret;

  pthread_mutex_t mutex;  //定义互斥锁
  pthread_mutex_init(&mutex,NULL);  //初始化

  //创建四个线程
  int i=0;
  for(;i<4;++i){
    ret=pthread_create(&tid[i],NULL,Thread_can,(void*)arg);
    if(ret!=0){
      perror("pthread_create error!\n");
      return -1;
    }
  }

  //线程等待
  for(i=0;i<4;++i){
    ret=pthread_join(tid[i],NULL);
  }


  //销毁锁
  pthread_mutex_destroy(&mutex);

  return 0;
}
